﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.DataLayer.ConnectionStrings;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities.ConnectionStrings;
using Sustainalytics.ESGRatings.BusinessLogic.ESGOnlineReport;
using Sustainalytics.Utils;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;

namespace Sustainalytics.HistoricalData.ReportGenerationTool
{
    public static class ClientDWConnection
    {
        public static string GetConnectionString()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;
            var connectionStringsManager =
                ConnectionStringsManager.GetInstance(ConnectionStringsRepository.GetInstance(connectionString));
            return connectionStringsManager.GetConnectionString(ConnectionStringType.ClientDW);
        }
    }

    public static class HistorycalDataConnectionString
    {
        public static string GetConnectionString()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;
            var connectionStringsManager =
                ConnectionStringsManager.GetInstance(ConnectionStringsRepository.GetInstance(connectionString));

            return connectionStringsManager.GetConnectionString(ConnectionStringType.DWArchive);
        }
    }
    class Program
    {



        static void Main(string[] args)
        {


            IRepositoryCollection<CorporateData> dwRep = new RepositoryCollection<CorporateData>(ClientDWConnection.GetConnectionString());
            IRepositoryCollection<CompanyHistoricalPerformance> companyHistoricalPerformanceLast36MonthsRepository = new RepositoryCollection<CompanyHistoricalPerformance>(HistorycalDataConnectionString.GetConnectionString());

            var businessLogicUnit = new HistoricalDataBusinessLogicUnit(companyHistoricalPerformanceLast36MonthsRepository);
            // IRepositoryCollection<CompanyHistoryData> companyHistoricalPerformanceRepository = new RepositoryCollection<CompanyHistoryData>(HistorycalDataConnectionString.GetConnectionString());

            //var companyHistoricalData = companyHistoricalPerformanceLast36MonthsRepository.ReadAll();
            var corporateDataLite = dwRep.ReadWhere(x => x.ComprehensiveEsgResearchState.ResearchState == ResearchState.ResearchAvailable, null, null, null, x => x.Id, x => x.ComprehensiveEsgResearchState.ResearchState == ResearchState.ResearchAvailable, x => x.ControversyResearchState.ResearchState == ResearchState.ResearchAvailable, x => x.CapitalIqId, x => x.CompanyName, x => x.CompanyType, x => x.GICSIndustryGroup, x => x.PeerGroupShortName, x => x.TemplateType, x => x.UniverseIds);

            //var items = from companyInfo in companyHistoricalData
            //    join corporateData in corporateDataLite on companyInfo.Id equals corporateData.Id
            //    select new {CompanyName = corporateData.CompanyName, Last36Months = companyInfo.Last36Months};

            //var reshapedItems=items.SelectMany(x=>x.Last36Months,(cn,info)=>new {cn.CompanyName,})


            string newFileName = "C:\\report_historical.csv";

            string headerRow = "CompanyId,CompanyName,Date,Overall Score,Environment Score, Social Score, GovernmentScore" + Environment.NewLine;
            if (File.Exists(newFileName))
            {
                File.WriteAllText(newFileName, string.Empty);
            }


            File.WriteAllText(newFileName, headerRow);



            Console.WriteLine("Started writing data...");
            foreach (var companies in corporateDataLite.Batch(200))
            {
                var companiesIds = companies.Select(x => x.Id).ToArray();
                var companiesNames = companies.ToDictionary(x => x.Id, x => x.CompanyName);
                var companyHistoricalInfo = businessLogicUnit.GetByIds(companiesIds);

                foreach (var info in companyHistoricalInfo.SelectMany(x => x.Value.Last36Months))
                {
                    string companyName;
                    if (companiesNames.TryGetValue(info.CompanyId, out companyName))
                    {
                        companyName = companyName.Replace(",", " ");
                        var row = string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", info.CompanyId, companyName, info.Date,
                            info.OverallScore, info.EnvironmentScore, info.SocialScore, info.GovernanceScore,
                            Environment.NewLine);

                        File.AppendAllText(newFileName, row);
                    }
                }

            }
            Console.WriteLine("Finished writing data!");
        }
    }
}
